<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Email as EmailModel;
use app\user\model\Continent as EmailLogModel;
use think\swoole\Task;
/**
 * 新闻控制器
 * @package app\user\admin
 */
class Email extends Admin
{
    /**
     * 消息列表
     * @author 李洪波 <361951119@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data_list = EmailModel::where($this->getMap())
            ->order($this->getOrder('id DESC'))
            ->paginate();
        $btn_send = [
            'title' => 'send',
            'icon'  => 'fa fa-fw fa-send',
            'href'  => url('send')
        ];
        return ZBuilder::make('table')
            ->setTableName('admin_emails')
            ->addTopButton('add',['title'=>'add'])
            ->addTopButton('delete',['title'=>'delete'])
            ->addTopButton('custom',$btn_send) // 添加发送按钮
            ->addRightButton('edit',['title'=>'edit'])
            ->addRightButton('delete',['title'=>'delete'])
            ->addColumns([
                ['id', 'ID'],
                ['first_name', 'first name'],
                ['last_name', 'last name'],
                ['email', 'email'],
                ['status', 'status', 'switch'],
                ['create_time', 'create time'],
                ['right_button', 'operation', 'btn'],
            ])
            ->addFilterList('status',['disable','enable'])
            ->setColumnWidth([
                'id'=>30,
                'create_time'=>100,
                'status'=>60,
                'right_button'=>50
            ])
            ->setRowList($data_list)
            ->fetch();
    }

    /**
     * 新增
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $data['first_name'] == '' && $this->error('Please fill in your first name');
            $data['last_name'] == '' && $this->error('Please fill in your last name');
            $data['email'] == '' && $this->error('Please fill in your email');
            isset($data['status'])?$data['status']=1:$data['status']=0;
            $list = [];
            $list['first_name']=$data['first_name'];
            $list['last_name']=$data['last_name'];
            $list['email']=$data['email'];
            $list['status']=$data['status'];
            $list['create_time']=date('Y-m-d H:i:s');

            $EmailModel = new EmailModel();
            if (false !== $EmailModel->save($list)) {
                $this->success('add success', 'index');
            } else {
                $this->error('add failed');
            }
        }

        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'first_name', 'first name'],
                ['text', 'last_name', 'last name'],
                ['text', 'email', 'email'],
            ])
            ->addSwitch('status', 'Status','',1)
            ->setPageTitle('Add')
            ->fetch();
    }

    public function edit($id = 0)
    {
        if ($id === 0) $this->error('missing parameter');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');

            // 验证
            $data['first_name'] == '' && $this->error('Please fill in your first name');
            $data['last_name'] == '' && $this->error('Please fill in your last name');
            $data['email'] == '' && $this->error('Please fill in your email');
            isset($data['status'])?$data['status']=1:$data['status']=0;
            if (EmailModel::update($data,['id'=>$id])) {
                $this->success('edit success', 'index');
            } else {
                $this->error('edit failed');
            }
        }

        // 获取数据
        $info = EmailModel::get($id);

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'first_name', 'first name'],
                ['text', 'last_name', 'last name'],
                ['text', 'email', 'email']
            ])
            ->addSwitch('status', 'Status','',1)
            ->setPageTitle('Edit')
            ->setFormData($info)
            ->fetch();
    }

    public function send(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['title'] == '' && $this->error('Please fill in the title');
            $data['content'] == '' && $this->error('Please fill in the content');
            $data['type'] == '' && $this->error('Please select at least one sending method');
            $list=[];
            $log['title']=$data['title'];
            $log['content']=$data['content'];
            $log['type']=$data['type']=='all'?1:2;
            $log['create_time']=date('Y-m-d H:i:s');
            if($data['type']=='all'){
                //发送给所有人
                $log['emails']=[];
                $emails=get_emails();
                foreach ($emails as $key=>$email){
                    $list[$key]['last_name']=$email['last_name'];
                    $list[$key]['first_name']=$email['first_name'];
                    $list[$key]['email']=$email['email'];
                    $list[$key]['title']=$data['title'];
                    $list[$key]['content']=$data['content'];

                }
            }else{
                if(!isset($data['ids'])) $this->error('Please select the sender');
                foreach ($data['ids'] as $key=>$id){
                    $info=EmailModel::get($id);
                    $log['emails'][]=$info['email'];
                    $list[$key]['last_name']=$info['last_name'];
                    $list[$key]['first_name']=$info['first_name'];
                    $list[$key]['email']=$info['email'];
                    $list[$key]['title']=$data['title'];
                    $list[$key]['content']=$data['content'];
                }
            }
            $log['emails']=json_encode($log['emails']);
            if(config('setting.is_sync')==1){
                foreach ($list as $val){
                    send_email($val['last_name'].' '.$val['first_name'],$val['title'],$val['content'],$val['email']);
                }
            }else {
                //异步发送
                if(!async_sned_email($list)) $this->error('Sending failed, connection timed out');
            }

            //添加发送成功日志
            $EmailLogModel = new EmailLogModel();
            $EmailLogModel->save($log);
            $this->success('send success', 'index');
        }
        $send_type = ['all' => 'All', 'other' => 'Part'];
        $emails=get_emails();
        $lists=[];
        foreach ($emails as $val){
            $lists[$val['id']]=$val['email'];
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'title', 'Title'],
                ['textarea', 'content', 'Content'],
            ])
            ->addSelect('type','Send Method','',$send_type)
            ->addSelect('ids','Select sender','',$lists,'','multiple')
            ->setTrigger('type', 'other', 'ids')
            ->setPageTitle('Send')
            ->fetch();
    }
}
